package com.kuiandjie.web;


import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.google.gson.Gson;
import com.kuiandjie.entity.Employee;
import com.kuiandjie.entity.Goal;
import com.kuiandjie.entity.Log;
import com.kuiandjie.entity.Project;
import com.kuiandjie.service.GoalService;
import com.kuiandjie.service.LogService;
import com.kuiandjie.util.DateUtil;

public class EditGoalServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		HttpSession session = request.getSession();
		String role = (String) session.getAttribute("role");
		
		if("leader".equals(role)) {
			String goalid = request.getParameter("gid");
	
			
			request.setAttribute("goalid", goalid);
			GoalService gs = new GoalService();
			Goal g = gs.findGoalById(goalid);
			request.setAttribute("g", g);
			if("POST".equals(request.getMethod())){
				response.setContentType("text/html");
				PrintWriter out = response.getWriter();
				
				String goalname = request.getParameter("goalname");
				String desc = request.getParameter("desc");
				
				
				if(g != null){
					g.setCreateTime(g.getCreateTime());
					g.setDesc(desc);
					g.setName(goalname);
					g.setProjectId(g.getProjectId());
					
					gs.editGoal(g);
					Project curp = (Project) session.getAttribute("curp");
					Employee e = (Employee) session.getAttribute("employee");
					Log log = new Log();
					log.setDesc("修改了目标<a href='projectdetail.jspx'>" + goalname + "</a>");
					log.setEmployeeId(e.getId());
					log.setProjectId(curp.getId());
					log.setTime(DateUtil.getNow());
					log.setName(e.getName());
					log.setPic(e.getPic());
					
					LogService ls = new LogService();
					ls.inserLog(log);
					
					request.setAttribute("msg", new Gson().toJson(log));
					request.getRequestDispatcher("msgflow.jspx").include(request, response);
					out.print("1");
					out.flush();
					out.close();
				}
				
			}else {
				request.getRequestDispatcher("WEB-INF/views/editgoal.jsp").forward(request, response);
			}
		} else {
			response.sendRedirect("projectdetail.jspx");
		}
	}
}


